package com.xinqi.modules.mq.delay.controller.inner;

import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.R;
import com.xinqi.common.base.utils.date.Dates;
import com.xinqi.common.rocketmq.dto.MqDelayMessage;
import com.xinqi.modules.mq.delay.MqDelayMessageConsumer;
import com.xinqi.modules.mq.delay.client.DelayMessageClient;
import com.xinqi.modules.mq.delay.dao.MqDelayMessageRepository;
import com.xinqi.modules.mq.delay.dto.MqDelayMessageDTO;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author linkai
 * @date 2023/11/19
 */
@Hidden
@Primary
@RestController
@RequiredArgsConstructor
public class MqDelayMessageInnerController implements DelayMessageClient {
    private final MqDelayMessageConsumer mqDelayMessageConsumer;
    private final MqDelayMessageRepository mqDelayMessageRepository;

    /**
     * 删除延时消息
     */
    @Override
    public R<Boolean> delete(String mqId) {
        return R.ok(mqDelayMessageRepository.updateIsDel(mqId) > 0);
    }

    /**
     * 添加延时消息
     */
    @Override
    public R<Boolean> create(MqDelayMessageDTO dto) {
        CommonErrors.BAD_REQUEST.check(StringUtils.isNotBlank(dto.getTopic()), "主题不能为空");
        CommonErrors.BAD_REQUEST.check(StringUtils.isNotBlank(dto.getKey()), "消息Key不能为空");
        CommonErrors.BAD_REQUEST.check(StringUtils.isNotBlank(dto.getBody()), "消息体不能为空");
        CommonErrors.BAD_REQUEST.check(dto.getArrivalTime() != null, "到达时间戳不能为空");
        MqDelayMessage delayMessage = MqDelayMessage.of(
            dto.getKey(), dto.getTag(),
            dto.getTopic(), dto.getBody(),
            Dates.localDateTime2Long(dto.getArrivalTime())
        );
        mqDelayMessageConsumer.sendDelayMessage(delayMessage);
        return R.ok();
    }
}
